package com.yishun.springboot.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.requestGwsLongGangQu.Vehicle;
import com.yinquan.util.GetNumber;
import com.yinquan.util.ImagesAndBase64Util;
import com.yinquan.util.ResultUtils;
import com.yishun.springboot.mapper.GwsLonggangquVehicleDetailedMapper;
import com.yishun.springboot.pojo.GwsLonggangquVehicleDetailed;
import com.yishun.springboot.pojo.PinyiVehicleDetailed;
import com.yishun.springboot.pojo.PinyiVehicleGetdata;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@Component
public class GwsLongGangQuTimingPushVehicleService {

	@Resource
	GwsLonggangquVehicleDetailedMapper gwsLonggangquVehicleDetailedMapper;

	// 可二选一填写(多少月内的数据)
	Integer howMouth = null;
	// 可二选一填写(多少日内的数据)
	Integer howDay = 30;

	ImagesAndBase64Util iu = new ImagesAndBase64Util();

	public String pushVehicleDetailed(JSONObject jsonObject) {
		String dateTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		log.info("开始推送车道闸基础信息到区工务署，当前时间：" + dateTime);

		String api_key = jsonObject.getString("apiKey");
		String eng_code = jsonObject.getString("engCode");
		String device_no = jsonObject.getString("deviceNo");
		String project_code = jsonObject.getString("projectCode");
		String api_version = jsonObject.getString("version");

		if (StringUtils.isEmpty(api_key) || StringUtils.isEmpty(eng_code) || StringUtils.isEmpty(api_version)
				|| StringUtils.isEmpty(device_no) || StringUtils.isEmpty(project_code)) {
			return JSONObject.toJSONString(ResultUtils.jsonFail(400), SerializerFeature.WriteMapNullValue);
		}

		PinyiVehicleDetailed projectDetaileds = gwsLonggangquVehicleDetailedMapper.findByRegionName(device_no);

		// no是给来推送给工务署那边的设备编号 当然自己库里也会存储这个编号 以及自己本库的编号
		String no = UUID.randomUUID().toString().replace("-", "");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("projectName", projectDetaileds.getRegionName());
		map.put("deviceNo", no);
		map.put("deviceCode", device_no);
		map.put("apiKey", api_key);
		map.put("engCode", eng_code);
		map.put("apiVersion", api_version);
		map.put("pushOrNot", 1);
		map.put("projectCode", project_code);
		Vehicle vehicle = new Vehicle();
		String res = vehicle.uploadVehicleBasic(api_version, no, api_key, project_code, eng_code, projectDetaileds);

		JSONObject paramJsonObject = JSONObject.parseObject(res);

		String code = paramJsonObject.getString("code");

		if (!code.equals("0")) {
			return JSONObject.toJSONString(ResultUtils.jsonFail("车道闸基础信息推送失败"), SerializerFeature.WriteMapNullValue);
		}

		int addRes = gwsLonggangquVehicleDetailedMapper.addBasicInfo(map);

		if (addRes < 1) {
			log.info("数据库新增失败，会导致无法上传车道闸基础信息数据");
			return JSONObject.toJSONString(ResultUtils.jsonFail("新增数据失败"), SerializerFeature.WriteMapNullValue);
		}

		return JSONObject.toJSONString(ResultUtils.jsonSuccess(), SerializerFeature.WriteMapNullValue);
	}

	@Async(value = "asyncExecutor")
	@Scheduled(fixedRate = 1000 * 60)
	public void heartbeat() {
		String dateTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		log.info("开始推送车道闸心跳到区工务署，当前时间：" + dateTime);
		int insertRecordNum = 0;// 计算一共推送几条数据过去

		// 查询出数据库正在推送数据的设备的key什么的
		List<GwsLonggangquVehicleDetailed> gwsLonggangquVehicleDetailedS = gwsLonggangquVehicleDetailedMapper
				.findByPushOrNot();
		// 用于接收查询出来的每一条数据给来推送心跳给工务署
		GwsLonggangquVehicleDetailed gwsLonggangquVehicleDetailed = new GwsLonggangquVehicleDetailed();
		Vehicle vehicle = new Vehicle();
		String resultStr = "";// 用于接收推送过去后的返回值
		String message = "";// 用于接收返回值里面的错误信息
		JSONObject resultJsonObject = new JSONObject();
		for (int i = 0; i < gwsLonggangquVehicleDetailedS.size(); i++) {
			gwsLonggangquVehicleDetailed = gwsLonggangquVehicleDetailedS.get(i);
			if (StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getDevice_no())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getApi_key())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getProject_code())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getEng_code())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getApi_version())) {

				continue;
			}
			resultStr = vehicle.httpPostVehicleDetailed(gwsLonggangquVehicleDetailed);
			resultJsonObject = JSONObject.parseObject(resultStr);
			message = resultJsonObject.getString("message");
			if (message.equals("已接收")) {
				log.info("本次推送成功");
				insertRecordNum++;
			}
		}
		log.info("车道闸心跳实时数据共推送：" + insertRecordNum);

	}

	@Scheduled(fixedRate = 1000 * 60 * 30)
	public void uploadData() {
		String dateTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		log.info("开始推送车辆入出场数据到区工务署，当前时间：" + dateTime);
		int insertRecordNum = 0;// 计算一共推送几条数据过去
		// 查询出数据库正在推送数据的设备的key什么的
		List<GwsLonggangquVehicleDetailed> gwsLonggangquVehicleDetailedS = gwsLonggangquVehicleDetailedMapper
				.findByPushOrNot();
		// 用于接收查询出来的每一条数据给来推送心跳给工务署
		GwsLonggangquVehicleDetailed gwsLonggangquVehicleDetailed = new GwsLonggangquVehicleDetailed();

		List<PinyiVehicleGetdata> pinyiGetData = null;

		JSONObject body = new JSONObject();
		JSONObject param = new JSONObject();

		String uploadPhotoUrl = "";
		String photoUrl = "";
		String carNumber = "";
		String deviceNo = "";
		String deviceDataTime = "";

		String message = "";

		Vehicle vehicle = new Vehicle();

		for (int i = 0; i < gwsLonggangquVehicleDetailedS.size(); i++) {
			gwsLonggangquVehicleDetailed = gwsLonggangquVehicleDetailedS.get(i);
			if (StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getDevice_no())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getApi_key())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getProject_code())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getEng_code())
					|| StringUtils.isEmpty(gwsLonggangquVehicleDetailed.getApi_version())) {

				continue;
			}

			if (howMouth == null && howDay == null) {
				log.warn("请规范填写获取信息根据天数/月份的选项");
				log.warn("--------------------结束~~~~~~~~~~~~~~~~");
				return;
			}
			if (howMouth != null && howDay != null) {
				log.warn("请规范填写获取信息根据天数/月份的选项");
				log.warn("--------------------结束~~~~~~~~~~~~~~~~");
				return;
			}
			if (howMouth != null && howMouth > 1) {
				log.warn("如若填写月份，请只需要填 howMouth 为 1 ");
				log.warn("--------------------结束~~~~~~~~~~~~~~~~");
				return;
			}
			if (howDay != null && howDay > 31) {
				log.warn("请填写31天内的天数 howDay");
				log.warn("--------------------结束~~~~~~~~~~~~~~~~");
				return;
			}
			if (howMouth != null) {
				pinyiGetData = gwsLonggangquVehicleDetailedMapper
						.findByGateNo(gwsLonggangquVehicleDetailedS.get(i).getDevice_code(), howMouth);
			}

			if (howDay != null) {
				pinyiGetData = gwsLonggangquVehicleDetailedMapper
						.findByGateNo(gwsLonggangquVehicleDetailedS.get(i).getDevice_code(), howDay);
			}

			if (pinyiGetData == null || pinyiGetData.size() == 0) {
				log.warn("本次没有获得数据！");
				log.warn("--------------------结束~~~~~~~~~~~~~~~~");
			}

			for (int j = 0; j < pinyiGetData.size(); j++) {

				String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

				Map<String, Object> imageParam1 = new HashMap<String, Object>();
				List<Map<String, Object>> imagesList = new ArrayList<Map<String, Object>>();

				param.put("api_key", gwsLonggangquVehicleDetailedS.get(i).getApi_key());
				param.put("project_code", gwsLonggangquVehicleDetailedS.get(i).getProject_code());
				param.put("eng_code", gwsLonggangquVehicleDetailedS.get(i).getEng_code());
				param.put("api_version", gwsLonggangquVehicleDetailedS.get(i).getApi_version());
				param.put("timestamp", timestamp);

				carNumber = pinyiGetData.get(j).getTruckNo();

				deviceDataTime = pinyiGetData.get(j).getRecognizeTime();
				if (pinyiGetData.get(j).getRecognizeTime().length() == 16) {
					deviceDataTime = pinyiGetData.get(j).getRecognizeTime() + ":" + GetNumber.getScopeNumber(1, 59);
				}

				// 换成假数据，后续可以if是十五高的项目就换
				deviceNo = gwsLonggangquVehicleDetailedS.get(i).getDevice_no();
//				deviceNo = (weiZhongYunVehicleDetailedToPinyiGetDataMapper.selectByDeviceNumber(deviceNo))
//						.getDeviceNumber();

				body.put("type", 1);// √
				body.put("plate_number", carNumber);// √

				body.put("direction", pinyiGetData.get(i).getInOrOut());// √
				// body.put("device_no", deviceNo); // √
				body.put("gate_no", deviceNo); // √
				body.put("region_no", "2");// √
				body.put("region_type", 1);// √
//				body.put("color", 1);// 车辆颜色：蓝，不是必填
//				body.put("lift_type", 1);// 抬杠方式：自动，不是必填
				body.put("region_name", gwsLonggangquVehicleDetailedS.get(i).getProject_name());// √
				body.put("lift_time", deviceDataTime);// √

				// 解碼成本地圖片，临时放文件到本地文件夹，然后上传到工务署
//			----start
				String tempData = (deviceDataTime + ".jpg").replace(":", "").replace(" ", "");
				photoUrl = ("E:\\uploadGWSImg\\" + deviceNo + tempData);
				photoUrl = iu.DecodeBase64(pinyiGetData.get(j).getPhoto(), photoUrl);
//			注释掉的
				// ---------end

				try {
					uploadPhotoUrl = vehicle.uploadImage(gwsLonggangquVehicleDetailedS.get(i).getApi_key(), photoUrl);
				} catch (Exception e) {
					log.error("图片上传到工务署时，结果为空/出现异常未上传." + "车牌号：" + carNumber + ".时间：" + deviceDataTime);
					log.error("异常：" + e.getMessage());
					continue;
				}

				imageParam1.put("img_type", 1);// √
				imageParam1.put("img_data", uploadPhotoUrl);
				imagesList.add(imageParam1);

				body.put("images", imagesList);
				message = vehicle.uploadData(param, body);

				if (!message.equals("已接收待处理")) {
					insertRecordNum++;
					continue;
				}

			}

		}

		log.info("车道闸出入场数据共推送：" + insertRecordNum);

	}

}
